package com.sgcc.ln.pmos.common.base;


import android.content.Intent;
import android.content.res.AssetManager;

import android.util.Log;
import android.view.View;
import android.webkit.MimeTypeMap;


import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.blankj.utilcode.util.UriUtils;
import com.github.barteksc.pdfviewer.PDFView;
import com.github.barteksc.pdfviewer.listener.OnLoadCompleteListener;
import com.github.barteksc.pdfviewer.listener.OnPageChangeListener;
import com.github.barteksc.pdfviewer.listener.OnPageErrorListener;
import com.sgcc.ln.pmos.arouter.common.CommonArouterPath;
import com.sgcc.pmos.nativesdk.R;
import com.sgcc.ln.pmos.common.widget.TitleBar;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Locale;


@Route(path = CommonArouterPath.COMMON_PDFPREVIEW)
public class PdfPreviewActivity extends BaseActivity implements OnPageChangeListener, OnLoadCompleteListener,
        OnPageErrorListener {

    private TitleBar mTitleBar;
    private PDFView mPdfView;
    private File outsideFile;

    @Autowired
    public String mFilePath;

    public File getOutsideFile() {
        return outsideFile;
    }

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.activity_pdfpreview;
    }

    @Override
    protected void initViews() {
        super.initViews();

        mTitleBar = (TitleBar) findViewById(R.id.title_bar);
        mPdfView = (PDFView) findViewById(R.id.pdfView);

        mTitleBar.setTitle("文件预览");
//        mTitleBar.setRightIcon(R.mipmap.go_main, new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                goMainActivity();
//            }
//        });

        mTitleBar.setRightText("···", new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                shareControl();
            }
        });
        File file;
        if (mFilePath.contains("/storage/emulated/0/Android/data/com.sgcc.ln.pmos.mobileapp/files/pdf")) {
            file = new File(mFilePath);
        } else {
            file = getAssetsFile(mFilePath);
        }
        outsideFile = file;
        mPdfView.fromFile(file)
                .defaultPage(0)
                .onPageChange(this)
                .enableAnnotationRendering(true)
                .onLoad(this)
                .spacing(10)
                .onPageError(this)
                .load();

    }

    public File getAssetsFile(String fileName) {
        try {
            AssetManager assetManager = mContext.getAssets();
            InputStream inputStream = assetManager.open(fileName);
            File tmp = new File(getExternalFilesDir("pdf"), fileName);
            OutputStream os = new FileOutputStream(tmp);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = inputStream.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            inputStream.close();
            return tmp;

        } catch (Exception e) {

        }
        return null;
    }

    @Override
    public void loadComplete(int nbPages) {

    }

    @Override
    public void onPageChanged(int page, int pageCount) {

    }

    @Override
    public void onPageError(int page, Throwable t) {

    }


    /**
     * 系统分享
     */
    public void shareControl() {
        Intent shareIntent = new Intent(Intent.ACTION_SEND);
        shareIntent.putExtra(Intent.EXTRA_STREAM,
                UriUtils.file2Uri(getOutsideFile()));
        shareIntent.setType(getMimeType(getOutsideFile()));//此处可发送多种文件
        startActivity(Intent.createChooser(shareIntent, "分享到"));
    }

    public static String getMimeType(File file) {
        String suffix = getSuffix(file);
        if (suffix == null) {
            return "*/*";
        }
        String type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(suffix);
        if (type != null || !type.isEmpty()) {
            return type;
        }
        return "*/*";
    }

    private static String getSuffix(File file) {
        if (file == null || !file.exists() || file.isDirectory()) {
            return null;
        }
        String fileName = file.getName();
        if (fileName.equals("") || fileName.endsWith(".")) {
            return null;
        }
        int index = fileName.lastIndexOf(".");
        if (index != -1) {
            return fileName.substring(index + 1).toLowerCase(Locale.US);
        } else {
            return null;
        }
    }


}
